package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.weightSheets;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xiaoxu.intranetweb.dom4jUtil.config.SystemConfigReader;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.WeightPicturesSamplingBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics.PoundQueryBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CCompanys;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.COrderDetail;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CWeightSheets;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysUser;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.COrderDetailMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CWeightPicturesSamplingMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CWeightSheetsMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICCompanysService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICOrderDetailService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICWeightSheetsService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.AnnualMoneyTrendVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetCWeightSheetsVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.WeighingSheetVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.YearOnYearReportVo;
import com.xiaoxu.intranetweb.mybatisplusWghticPicdb.entity.WeightPictures;
import com.xiaoxu.intranetweb.mybatisplusWghticPicdb.mapper.WeightPicturesMapper;
import com.xiaoxu.intranetweb.util.StringUtils;
import com.xiaoxu.intranetweb.util.SzResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.checkerframework.checker.units.qual.A;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Component
@Slf4j
public class WeightSheetsBu {
    @Autowired
    private ICWeightSheetsService weightSheetsService;
    @Autowired
    private ICOrderDetailService orderDetailService;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private PoundQueryBu poundQueryBu;
    @Autowired
    private ICProductsInfoService productsInfoService;
    @Autowired
    private ICAshGateVideoBindService ashGateVideoBindService;
    @Autowired
    private ICCompanysService companysService;
    @Autowired
    private ICPdtsAuthService pdtsAuthService;
    @Autowired
    private ITExcelTemplatesService excelTemplatesService;
    @Autowired
    private ITApproveService approveService;
    @Autowired
    private ISysUserPlantConnService userPlantConnService;
    @Autowired
    private ITApproveInfoService approveInfoService;
    @Autowired
    private ICIcCardsInfoService icCardsInfoService;
    @Autowired
    private ICCompanyClassService companyClassService;
    @Autowired
    private COrderDetailMapper orderDetailMapper;
    @Autowired
    private CWeightSheetsMapper cWeightSheetsMapper;
    @Autowired
    private WeightPicturesMapper weightPicturesMapper;
    @Autowired
    private CWeightPicturesSamplingMapper cWeightPicturesSamplingMapper;
    @Autowired
    private SystemConfigReader systemConfigReader;
    //    删除磅单
    @Transactional
    public SzResult deleteWeightSheets(String id, String userId, String reason, String token, String plantId) throws Exception {
        // String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        if (reason == null) {
            return SzResult.error("请输入理由");
        }
//        避免重复删除
        QueryWrapper<CWeightSheets> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", id);
        queryWrapper2.eq("WEISHT_DELETED", 1);
        queryWrapper2.eq("DATA_FROM", plantId);
        if (weightSheetsService.getOne(queryWrapper2) != null) {
            return SzResult.error("该磅单已删除");
        }
        QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("DATA_FROM", plantId);
        CWeightSheets cWeightSheets = weightSheetsService.getOne(queryWrapper);
        cWeightSheets.setWeishtDeleted(1);
        cWeightSheets.setDownedID1(0);
        weightSheetsService.updateById(cWeightSheets);
        //        如果是进货类，直接删就行了
        if (cWeightSheets.getWeishtProduct().contains(".")) {
            sysLogBu.logRecord("删除磅单", sysUser.getTrueName(), "删除了磅单" + cWeightSheets.getWeishtSheetno() + ",退回【" + cWeightSheets.getWeishtCo() + cWeightSheets.getWeishtChiCo() + "】账户" + cWeightSheets.getWeishtMoney() + "元" + "理由是:" + reason, plantId);
            return SzResult.Success();
        }
        QueryWrapper<CCompanys> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("CPY_CO", cWeightSheets.getWeishtCoSupply());
        queryWrapper3.eq("CPY_CHICO", cWeightSheets.getWeishtCoSupplyChi());
        queryWrapper3.eq("DATA_FROM", cWeightSheets.getDataFrom());
        queryWrapper3.eq("CPY_DELETED", 0);
        CCompanys cCompanys = companysService.getOne(queryWrapper3);
        if (cCompanys == null) {
            throw new Exception("供货单位不存在");
        }

//        将钱退回账户
        QueryWrapper<COrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ORDETAIL_CO", cWeightSheets.getWeishtCo());
        queryWrapper1.eq("ORDETAIL_CHICO", cWeightSheets.getWeishtChiCo());
        queryWrapper1.eq("ORDETAIL_SUB_ID", cCompanys.getId());
        queryWrapper1.eq("DATA_FROM", cWeightSheets.getDataFrom());
        queryWrapper1.eq("ORDETAIL_DELETED", 0);
        COrderDetail cOrderDetail = orderDetailService.getOne(queryWrapper1);
//      COrderDetail表的  ORDETAIL_REMAIN_NUM是余额，cWeightSheets表的WEISHT_MONEY是磅单金额都是BigDecimal类型
    /*    cOrderDetail.setOrdetailRemainNum(cOrderDetail.getOrdetailRemainNum().add(cWeightSheets.getWeishtMoney()));
        orderDetailService.updateById(cOrderDetail);*/
        String weishtMoney = cWeightSheets.getWeishtMoney().toString();
        String cOrderDetailId = cOrderDetail.getId();
        UpdateWrapper<COrderDetail> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ID", cOrderDetail.getId());
        updateWrapper.set("DownedID1", 0);
        orderDetailService.update(updateWrapper);
        orderDetailMapper.updateOrderDetailForDelete(new BigDecimal(weishtMoney), cOrderDetailId);
        sysLogBu.logRecord("删除磅单", sysUser.getTrueName(), "删除了磅单" + cWeightSheets.getWeishtSheetno() + ",退回【" + cWeightSheets.getWeishtCo() + cWeightSheets.getWeishtChiCo() + "】账户" + cWeightSheets.getWeishtMoney() + "元" + "理由是:" + reason, plantId);
        return SzResult.Success();
    }


    //单据调价
    @Transactional
    public SzResult updateWeightSheetsPrice(String price, List<String> weishtSheetnos, String userId, String plantId) throws Exception {
        QueryWrapper<SysUserPlantConn> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("USER_ID", userId);
        queryWrapper3.eq("PLANT_ID", plantId);
        SysUserPlantConn sysUserPlantConn = userPlantConnService.getOne(queryWrapper3);
        if (sysUserPlantConn == null) {
            return SzResult.error("该用户未绑定对应工厂");
        }
        // String plantId = sysUserPlantConn.getPlantId();

        QueryWrapper<SysUser> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("ID", userId);
        SysUser user = userInfoDao.getUser(userId);

        StringBuilder logMsg = new StringBuilder();
        SysUser sysUser = userInfoDao.getUser(userId);
        QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("WEISHT_SHEETNO", weishtSheetnos);
        queryWrapper.eq("WEISHT_DELETED", 0);
        List<CWeightSheets> cWeightSheets = weightSheetsService.list(queryWrapper);
        List<String> no = new ArrayList<>();
        for (CWeightSheets cWeightSheet : cWeightSheets) {
            no.add(cWeightSheet.getWeishtSheetno());
        }
        //审批
        QueryWrapper<TApprove> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("IF_ON", 1);
        queryWrapper4.eq("DEL_FLAG", 0);
        queryWrapper4.eq("DATA_FROM", plantId);
        queryWrapper4.eq("APPROVE_NAME", "updateWeightSheetPrice");
        TApprove tApprove = approveService.getOne(queryWrapper4);
        if (tApprove != null) {//开启了审批，创建审批信息
            TApproveInfo tApproveInfo = new TApproveInfo();
            tApproveInfo.setApproveId(tApprove.getId());
            tApproveInfo.setApproveTier(tApprove.getApproveTier());
            tApproveInfo.setApproveState(0);
            tApproveInfo.setCreateBy(user.getTrueName());
            tApproveInfo.setCreateTime(LocalDateTime.now());
            tApproveInfo.setDelFlag(0);
            tApproveInfo.setApproveRemark("");
            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的单据调价审批：【" + "将" + no + "磅单的价格" + "修改为" + price + "】");
            tApproveInfo.setDataFrom(plantId);
            Map<String, Object> map = new HashMap<>();
            map.put("trueName", user.getTrueName());
            map.put("price", price);
            map.put("plantId", plantId);
            map.put("weishtSheetnos", weishtSheetnos);
            map.put("userId", userId);
            String s = JSON.toJSONString(map);
            tApproveInfo.setExecutionData(s);
            approveInfoService.save(tApproveInfo);
            return SzResult.Error("该功能需审批,请等待审批");
        }
        for (CWeightSheets cWeightSheets1 : cWeightSheets) {
//            老钱
            String oldMoney = cWeightSheets1.getWeishtMoney().toString();

            //        logMsg里记录一下磅单号，由什么价格调整为什么价格
            logMsg.append("磅单号【").append(cWeightSheets1.getWeishtSheetno()).append("】由").append(cWeightSheets1.getWeishtPrice()).append("调整为").append(price).append(";");
            cWeightSheets1.setWeishtPrice(new BigDecimal(price));
//            将这一单的钱改变
            cWeightSheets1.setWeishtMoney(new BigDecimal(price).multiply(cWeightSheets1.getWeishtNetWght()));
//            新钱
            String newMoney = cWeightSheets1.getWeishtMoney().toString();
            cWeightSheets1.setDownedID1(0);

            weightSheetsService.updateById(cWeightSheets1);
            QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("CPY_CO", cWeightSheets1.getWeishtCoSupply());
            queryWrapper2.eq("CPY_CHICO", cWeightSheets1.getWeishtCoSupplyChi());
            queryWrapper2.eq("DATA_FROM", cWeightSheets1.getDataFrom());
            queryWrapper2.eq("CPY_DELETED", 0);
            CCompanys cCompanys = companysService.getOne(queryWrapper2);
            if (cCompanys == null) {
                throw new Exception("供货单位不存在");
            }
            //         将钱退回账户
            QueryWrapper<COrderDetail> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("ORDETAIL_CO", cWeightSheets1.getWeishtCo());
            queryWrapper1.eq("ORDETAIL_CHICO", cWeightSheets1.getWeishtChiCo());
            queryWrapper1.eq("ORDETAIL_SUB_ID", cCompanys.getId());
            queryWrapper1.eq("DATA_FROM", cWeightSheets1.getDataFrom());
            queryWrapper1.eq("ORDETAIL_DELETED", 0);
            COrderDetail cOrderDetail = orderDetailService.getOne(queryWrapper1);
//      COrderDetail表的  ORDETAIL_REMAIN_NUM是余额，cWeightSheets表的WEISHT_MONEY是磅单金额都是BigDecimal类型
//            cOrderDetail.setOrdetailRemainNum(cOrderDetail.getOrdetailRemainNum().add(cWeightSheets1.getWeishtMoney()));加一个负数
 /*           cOrderDetail.setOrdetailRemainNum(cOrderDetail.getOrdetailRemainNum().add(BigDecimal.valueOf(Double.parseDouble(oldMoney)).subtract(BigDecimal.valueOf(Double.parseDouble(newMoney)))));
            orderDetailService.updateById(cOrderDetail);*/
            String cOrderDetailId = cOrderDetail.getId();

            UpdateWrapper<COrderDetail> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("ID", cOrderDetail.getId());
            updateWrapper.set("DownedID1", 0);
            orderDetailService.update(updateWrapper);

            // 执行两个步骤的更新操作
            orderDetailMapper.refundOldDeduction(new BigDecimal(oldMoney), cOrderDetailId); // 退还旧的扣款
            orderDetailMapper.applyNewDeduction(new BigDecimal(newMoney), cOrderDetailId);  // 应用新的扣款

        }
        sysLogBu.logRecord("单据调价", sysUser.getTrueName(), "调价了" + weishtSheetnos.size() + "条磅单，" + logMsg, plantId);
        return SzResult.Success();
    }

    //单据一键调价
    @Transactional
    public SzResult updateWeightSheetsPriceAll(String price, String userId, String fullTimeStart, String fullTimeEnd,
                                               String coSupply, String coSupplyChi, String co, String chiCo, String product, String truckno, String operator, String sheetno, String reason, String iccardno, Integer isEmpty, String plantId) throws Exception {

        StringBuilder logMsg = new StringBuilder();
        QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("WEISHT_FULL_TM");
//        根据时间重车起止
        queryWrapper.between(fullTimeStart != null && !fullTimeStart.equals("") && fullTimeEnd != null && !fullTimeEnd.equals(""), "WEISHT_FULL_TM", fullTimeStart, fullTimeEnd);
//        开始时间往后
        queryWrapper.ge(fullTimeStart != null && !fullTimeStart.equals(""), "WEISHT_FULL_TM", fullTimeStart);
//        结束时间往前
        queryWrapper.le(fullTimeEnd != null && !fullTimeEnd.equals(""), "WEISHT_FULL_TM", fullTimeEnd);
//WEISHT_BACKED不等于0表示车辆已经回磅
        queryWrapper.eq("WEISHT_BACKED", 1);
//        不返回已删除的榜单
        queryWrapper.eq("WEISHT_DELETED", 0);
//        根据供货单位查询
        queryWrapper.like(coSupply != null && !coSupply.equals(""), "WEISHT_CO_SUPPLY", coSupply);
        queryWrapper.eq(coSupplyChi != null && !coSupplyChi.equals(""), "WEISHT_CO_SUPPLY_CHI", coSupplyChi);
//        根据收货单位查询
        queryWrapper.eq(co != null && !co.equals(""), "WEISHT_CO", co);
        queryWrapper.eq(chiCo != null && !chiCo.equals(""), "WEISHT_CHI_CO", chiCo);
//        根据卡号查询
        queryWrapper.eq(iccardno != null && !iccardno.equals(""), "WEISHT_ICCARDNO", iccardno);
//        根据品种查询
        queryWrapper.in(product != null && !product.equals(""), "WEISHT_PRODUCT", product);
//        根据车号查询
        queryWrapper.like(truckno != null && !truckno.equals(""), "WEISHT_TRUCKNO", truckno);
//        根据操作员查询
        queryWrapper.like(operator != null && !operator.equals(""), "WEISHT_OPERATOR", operator);
//        根据单号查询
        queryWrapper.eq(sheetno != null && !sheetno.equals(""), "WEISHT_SHEETNO", sheetno);
//        根据1备注查询
        queryWrapper.like(reason != null && !reason.equals(""), "WEISHT_MODIFY_REASON", reason);
//        根据是否空车查询
        if (isEmpty != null) {
            if (isEmpty == 0) {
//                WEISHT_NET_WGHT大于0表示重车
                queryWrapper.gt("WEISHT_NET_WGHT", 0);
            }
        }
        List<CWeightSheets> cWeightSheets = weightSheetsService.list(queryWrapper);
        List<String> no = new ArrayList<>();
        for (CWeightSheets cWeightSheet : cWeightSheets) {
            no.add(cWeightSheet.getWeishtSheetno());
        }
        SysUser sysUser = userInfoDao.getUser(userId);
        QueryWrapper<SysUserPlantConn> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("USER_ID", userId);
        SysUserPlantConn sysUserPlantConn = userPlantConnService.getOne(queryWrapper3);
        if (sysUserPlantConn == null) {
            return SzResult.error("该用户没有绑定工厂");
        }
        //String plantId = sysUserPlantConn.getPlantId();
        QueryWrapper<SysUser> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("ID", userId);
        SysUser user = userInfoDao.getUser(userId);
        //审批
        QueryWrapper<TApprove> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("IF_ON", 1);
        queryWrapper4.eq("DEL_FLAG", 0);
        queryWrapper4.eq("DATA_FROM", plantId);
        queryWrapper4.eq("APPROVE_NAME", "updateWeightSheetPriceAll");
        TApprove tApprove = approveService.getOne(queryWrapper4);
        if (tApprove != null) {//开启了审批，创建审批信息
            TApproveInfo tApproveInfo = new TApproveInfo();
            tApproveInfo.setApproveId(tApprove.getId());
            tApproveInfo.setApproveTier(tApprove.getApproveTier());
            tApproveInfo.setApproveState(0);
            tApproveInfo.setCreateBy(user.getTrueName());
            tApproveInfo.setCreateTime(LocalDateTime.now());
            tApproveInfo.setDelFlag(0);
            tApproveInfo.setApproveRemark("");
            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的一键调价审批：【" + "将" + no + "磅单" + "(" + fullTimeStart + "-" + fullTimeEnd + "期间)" + "的价格" + "修改为" + price + "】");
            tApproveInfo.setDataFrom(plantId);
            Map<String, Object> map = new HashMap<>();

            map.put("trueName", user.getTrueName());
            map.put("price", price);
            map.put("plantId", plantId);
            map.put("weishtSheetnos", no);
            map.put("userId", userId);
            map.put("fullTimeStart", fullTimeStart);
            map.put("fullTimeEnd", fullTimeEnd);
            map.put("coSupply", coSupply);
            map.put("coSupplyChi", coSupplyChi);
            map.put("co", co);
            map.put("chiCo", chiCo);
            map.put("product", product);
            map.put("truckno", truckno);
            map.put("operator", operator);
            map.put("sheetno", sheetno);
            map.put("reason", reason);
            map.put("iccardno", iccardno);
            map.put("isEmpty", isEmpty);

            String s = JSON.toJSONString(map);
            tApproveInfo.setExecutionData(s);
            approveInfoService.save(tApproveInfo);
            return SzResult.Error("该功能需审批,请等待审批");
        }


        for (CWeightSheets cWeightSheets1 : cWeightSheets) {
//            老钱
            String oldMoney = cWeightSheets1.getWeishtMoney().toString();
            //        logMsg里记录一下磅单号，由什么价格调整为什么价格
            logMsg.append("磅单号【").append(cWeightSheets1.getWeishtSheetno()).append("】由").append(cWeightSheets1.getWeishtPrice()).append("调整为").append(price).append(";");
            cWeightSheets1.setWeishtPrice(new  BigDecimal(price));
            //            将这一单的金额改变
            cWeightSheets1.setWeishtMoney(new BigDecimal(price).multiply(cWeightSheets1.getWeishtNetWght()));
            //            新钱
            String newMoney = cWeightSheets1.getWeishtMoney().toString();
            cWeightSheets1.setDownedID1(0);
            weightSheetsService.updateById(cWeightSheets1);
            QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("CPY_CO", cWeightSheets1.getWeishtCoSupply());
            queryWrapper2.eq("CPY_CHICO", cWeightSheets1.getWeishtCoSupplyChi());
            queryWrapper2.eq("DATA_FROM", cWeightSheets1.getDataFrom());
            queryWrapper2.eq("CPY_DELETED", 0);
            CCompanys cCompanys = companysService.getOne(queryWrapper2);
            if (cCompanys == null) {
                return SzResult.error("供货单位不存在");
            }
            //         将钱退回账户
            QueryWrapper<COrderDetail> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("ORDETAIL_CO", cWeightSheets1.getWeishtCo());
            queryWrapper1.eq("ORDETAIL_CHICO", cWeightSheets1.getWeishtChiCo());
            queryWrapper1.eq("ORDETAIL_SUB_ID", cCompanys.getId());
            queryWrapper1.eq("DATA_FROM", cWeightSheets1.getDataFrom());
            queryWrapper1.eq("ORDETAIL_DELETED", 0);
            COrderDetail cOrderDetail = orderDetailService.getOne(queryWrapper1);
//      COrderDetail表的  ORDETAIL_REMAIN_NUM是余额，cWeightSheets表的WEISHT_MONEY是磅单金额都是BigDecimal类型
 /*           cOrderDetail.setOrdetailRemainNum(cOrderDetail.getOrdetailRemainNum().add(BigDecimal.valueOf(Double.parseDouble(oldMoney)).subtract(BigDecimal.valueOf(Double.parseDouble(newMoney)))));
            orderDetailService.updateById(cOrderDetail);*/
            String cOrderDetailId = cOrderDetail.getId();

            UpdateWrapper<COrderDetail> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("ID", cOrderDetail.getId());
            updateWrapper.set("DownedID1", 0);
            orderDetailService.update(updateWrapper);
            // 执行两个步骤的更新操作
            orderDetailMapper.refundOldDeduction(new BigDecimal(oldMoney), cOrderDetailId); // 退还旧的扣款
            orderDetailMapper.applyNewDeduction(new BigDecimal(newMoney), cOrderDetailId);  // 应用新的扣款
        }
        sysLogBu.logRecord("单据调价", sysUser.getTrueName(), "调价了" + cWeightSheets.size() + "条磅单，" + logMsg, plantId);
        return SzResult.Success();
    }

    /**
     * 退货或换货
     *
     * @param weishtSheetNo    单号
     * @param ReturnOrExchange 1是退货，2是换货
     * @param exchangePdtId    换货的品种id
     * @param token
     * @return
     */
    public SzResult pdtReturnOrExchange(String weishtSheetNo, Integer ReturnOrExchange, String exchangePdtId, String reason, String token, String plantId) throws Exception {
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        String uuid = java.util.UUID.randomUUID().toString().replace("-", "");
        if (reason == null) {
            return SzResult.error("请输入理由");
        }
//        } else {
//            sysLogBu.logRecord("单据退换货理由", sysUser.getTrueName(), reason, plantId);
//        }
        int exchangePdtStockcls = 2;
        if (ReturnOrExchange == 2) {
            QueryWrapper<CProductsInfo> queryWrapperPdt = new QueryWrapper<>();
            queryWrapperPdt.eq("PDTINF_ID", exchangePdtId);
            queryWrapperPdt.eq("PDTINF_DELETED", 0);
            queryWrapperPdt.eq("DATA_FROM", plantId);
            CProductsInfo exchangePdt = productsInfoService.getOne(queryWrapperPdt);
            exchangePdtStockcls = exchangePdt.getPdtinfStockcls();//0是出货类，1是进货类
        }
//        weishtSheetNo如果存在TH，不给操作了
        if (weishtSheetNo.contains("TH")) {
            return SzResult.error("该单已经退货了");
        }
//        weishtSheetNo如果存在HH，不给操作了
        if (weishtSheetNo.contains("HH")) {
            return SzResult.error("该单已经换货了");
        }
//        再查询weishtSheetNo是否存在拼接TH的单号或者HH的单号
        QueryWrapper<CWeightSheets> queryWrapper10 = new QueryWrapper<>();
//        queryWrapper.eq("WEISHT_SHEETNO", weishtSheetNo+"TH");
//        weishtSheetNo加TH或者HH，使用箭头函数
        queryWrapper10.and(i -> i.eq("WEISHT_SHEETNO", weishtSheetNo + "TH").or().eq("WEISHT_SHEETNO", weishtSheetNo + "HH"));
        queryWrapper10.eq("WEISHT_DELETED", 0);
        List<CWeightSheets> list = weightSheetsService.list(queryWrapper10);
        if (!list.isEmpty()) {
            return SzResult.error("该单已经退货或换货了");
        }

        QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("WEISHT_SHEETNO", weishtSheetNo);
        queryWrapper.eq("WEISHT_DELETED", 0);
        CWeightSheets cWeightSheets = weightSheetsService.getOne(queryWrapper);
        if (cWeightSheets == null) {
            return SzResult.error("没有找到该磅单");
        }
        String weishtProduct = cWeightSheets.getWeishtProduct();//拿到磅单上的品种weishtProduct
        QueryWrapper<CProductsInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("PDTINF_PDT", weishtProduct);
        CProductsInfo cProductsInfo = productsInfoService.getOne(queryWrapper1);
        int inOrOut = cProductsInfo.getPdtinfStockcls();//查看该品种是出货类还是进货类
        BigDecimal weishtNetWght1 = cWeightSheets.getWeishtNetWght();//原来的净重
        weishtNetWght1 = weishtNetWght1.multiply(BigDecimal.valueOf(-1));//净重的负数
        BigDecimal multiply = cWeightSheets.getWeishtPrice().multiply(weishtNetWght1);

        if (inOrOut == 0) {//出货类
            if (ReturnOrExchange == 1) {//退货

                //判断该磅单是否已经退货
                QueryWrapper<CWeightSheets> queryWrapperTHJudge = new QueryWrapper<>();
                queryWrapperTHJudge.eq("WEISHT_SHEETNO", cWeightSheets.getWeishtSheetno() + "TH");
                queryWrapperTHJudge.eq("WEISHT_DELETED", 0);
                CWeightSheets cWeightSheetsTHJudge = weightSheetsService.getOne(queryWrapperTHJudge);
                if (cWeightSheetsTHJudge != null) {
                    return SzResult.error("该磅单已经退货");
                }
                //自己本身不能为退货的磅单
                if (cWeightSheets.getWeishtSheetno().contains("TH")) {
                    return SzResult.error("该磅单为退货单，不能再次退货");
                }
                CWeightSheets cWeightSheets1 = new CWeightSheets();
                cWeightSheets1.setId(cWeightSheets.getWeishtSheetno() + "TH");
                cWeightSheets1.setWeishtYearSn(cWeightSheets.getWeishtYearSn());
                cWeightSheets1.setWeishtTruckno(cWeightSheets.getWeishtTruckno());//退货的车号等于原来的车号
                cWeightSheets1.setWeishtGrossWght(weishtNetWght1);//退货的毛重等于原来的净重的负数
                cWeightSheets1.setWeishtTare(BigDecimal.ZERO);//退货的皮重为0
                cWeightSheets1.setWeishtNetWght(weishtNetWght1);//退货的净重
                cWeightSheets1.setWeishtMoney(multiply);
                cWeightSheets1.setWeishtPrice(cWeightSheets.getWeishtPrice());//退货的价格等于原来的价格
                cWeightSheets1.setWeishtSheetno(cWeightSheets.getWeishtSheetno() + "TH");//退货的磅单号为原来的磅单号+TH
                cWeightSheets1.setWeishtIccardno(cWeightSheets.getWeishtIccardno());//退货的卡号等于原来的卡号
                cWeightSheets1.setWeishtProduct(cWeightSheets.getWeishtProduct());//退货的品种等于原来的品种
                cWeightSheets1.setWeishtCo(cWeightSheets.getWeishtCo());//退货的客户等于原来的客户
                cWeightSheets1.setWeishtChiCo(cWeightSheets.getWeishtChiCo());//退货的子客户等于原来的子客户
                cWeightSheets1.setWeishtCoSupply(cWeightSheets.getWeishtCoSupply());//退货的供应商等于原来的供应商
                cWeightSheets1.setWeishtCoSupplyChi(cWeightSheets.getWeishtCoSupplyChi());//退货的子供应商等于原来的子供应商
                cWeightSheets1.setWeishtEnterTm(cWeightSheets.getWeishtEnterTm());
                cWeightSheets1.setWeishtOutTm(cWeightSheets.getWeishtOutTm());
                cWeightSheets1.setWeishtEmptyTm(cWeightSheets.getWeishtEmptyTm());
                cWeightSheets1.setWeishtFullTm(cWeightSheets.getWeishtFullTm());
                cWeightSheets1.setWeishtLoadTm(cWeightSheets.getWeishtLoadTm());
                cWeightSheets1.setWeishtLoadEndTm(cWeightSheets.getWeishtLoadEndTm());
                cWeightSheets1.setWeishtOperator(cWeightSheets.getWeishtOperator());
                cWeightSheets1.setWeishtAshgateId(cWeightSheets.getWeishtAshgateId());
                cWeightSheets1.setWeishtRemark(cWeightSheets.getWeishtRemark());
                cWeightSheets1.setWeishtBacked(true);
                cWeightSheets1.setWeishtDeleted(0);
                cWeightSheets1.setDownedID1(0);
                cWeightSheets1.setDataFrom(plantId);
                cWeightSheets1.setWeishtTranMode(cWeightSheets.getWeishtTranMode());
                cWeightSheets1.setWeishtIccardtype(cWeightSheets.getWeishtIccardtype());
                cWeightSheets1.setWeishtTruckSn(cWeightSheets.getWeishtTruckSn());
                weightSheetsService.save(cWeightSheets1);
                //退货后，将钱退回账户
                QueryWrapper<COrderDetail> queryWrapper2 = new QueryWrapper<>();
                String weishtCoSupply = cWeightSheets.getWeishtCoSupply();
                QueryWrapper<CCompanys> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("CPY_CO", weishtCoSupply);
                CCompanys one = companysService.getOne(queryWrapper3);
                String cpyId = String.valueOf(one.getCpyId());
                queryWrapper2.eq("ORDETAIL_CO", cWeightSheets1.getWeishtCo());
                queryWrapper2.eq("ORDETAIL_CHICO", cWeightSheets1.getWeishtChiCo());
                queryWrapper2.eq("ORDETAIL_DELETED", 0);
                queryWrapper2.eq("ORDETAIL_SUB_ID", cpyId);
                COrderDetail cOrderDetail = orderDetailService.getOne(queryWrapper2);
                BigDecimal weishtMoney = cWeightSheets1.getWeishtMoney();//退货的钱（负数）
//                cOrderDetail.setOrdetailRemainNum(cOrderDetail.getOrdetailRemainNum().subtract(weishtMoney));//余额-这个负的金额
//                cOrderDetail.setDownedID1(0);
//                orderDetailService.updateById(cOrderDetail);
                String cOrderDetailId = cOrderDetail.getId();

                UpdateWrapper<COrderDetail> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("ID", cOrderDetail.getId());
                updateWrapper.set("DownedID1", 0);
                orderDetailService.update(updateWrapper);
                orderDetailMapper.updateOrderDetailForPdtReturnOrExchange(weishtMoney, cOrderDetailId);

                sysLogBu.logRecord("单据退货", sysUser.getTrueName(), "退货了" + "磅单为" + weishtSheetNo + "的磅单" + "理由是:" + reason, plantId);
            } else {//换货  exchangePdt(换货的品种)
                //只能换出货类的货物
                if (exchangePdtStockcls == 1) {
                    return SzResult.error("该品种不是出货类货物，不可换货");
                }
                QueryWrapper<CWeightSheets> queryWrapper5 = new QueryWrapper<>();
                queryWrapper5.eq("WEISHT_SHEETNO", weishtSheetNo + "HH");
                queryWrapper5.eq("WEISHT_DELETED", 0);
                CWeightSheets cWeightSheets3 = weightSheetsService.getOne(queryWrapper5);
                if (cWeightSheets3 != null && cWeightSheets3.getWeishtSheetno().contains("HH")) {
                    return SzResult.error("该磅单已换货,不可再换货");
                }
                QueryWrapper<CWeightSheets> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("WEISHT_SHEETNO", weishtSheetNo + "TH");
                queryWrapper2.eq("WEISHT_DELETED", 0);
                CWeightSheets cWeightSheets1 = weightSheetsService.getOne(queryWrapper2);
                if (cWeightSheets1 != null && cWeightSheets1.getWeishtSheetno().contains("TH")) {
                    return SzResult.error("该磅单已退货,不可再换货");
                }

                //没退货没换货
                QueryWrapper<CProductsInfo> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("PDTINF_ID", exchangePdtId);
                queryWrapper3.eq("PDTINF_DELETED", 0);
                //queryWrapper3.ne("PDTINF_PDT", weishtProduct);
                CProductsInfo cProductsInfo1 = productsInfoService.getOne(queryWrapper3);//换货的品种
                String pdtinfSubjectId = cProductsInfo1.getPdtinfSubjectId();//单位id
                QueryWrapper<CCompanys> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("ID", pdtinfSubjectId);
                queryWrapper4.eq("CPY_DELETED", 0);
//                CCompanys cCompanys = companysService.getOne(queryWrapper4);//单位
//                String cpyCo = cCompanys.getCpyCo();//单位名称
//                String weishtCo = cWeightSheets.getWeishtCo();
//                if (!cpyCo.equals(weishtCo)) {
//                    return SzResult.error("该品种未授权给该单位");
//                }
                if (cProductsInfo1.getPdtinfStockcls() != 0) {
                    return SzResult.error("该品种不是出货类货物，不可换货");
                }
                //进行换货
                QueryWrapper<CPdtsAuth> queryWrapperAuth = new QueryWrapper<>();
                queryWrapperAuth.eq("PDTSAUTH_PDT", cProductsInfo1.getPdtinfPdt());
                queryWrapperAuth.eq("PDTSAUTH_CO", cWeightSheets.getWeishtCo());
                queryWrapperAuth.eq("PDTSAUTH_CHICO", cWeightSheets.getWeishtChiCo());
                queryWrapperAuth.eq("PDTSAUTH_DELETED", 0);
                CPdtsAuth auth = pdtsAuthService.getOne(queryWrapperAuth);
                if (auth == null) {
                    return SzResult.error("该品种未授权给该单位");
                }
                //先退货
                CWeightSheets cWeightSheets2 = new CWeightSheets();
                cWeightSheets2.setId(cWeightSheets.getWeishtSheetno() + "TH");
                cWeightSheets2.setWeishtYearSn(cWeightSheets.getWeishtYearSn());
                cWeightSheets2.setWeishtTruckno(cWeightSheets.getWeishtTruckno());//退货的车号等于原来的车号
                cWeightSheets2.setWeishtGrossWght(weishtNetWght1);//退货的毛重等于原来的净重的负数
                cWeightSheets2.setWeishtTare(BigDecimal.ZERO);//退货的皮重为0
                cWeightSheets2.setWeishtNetWght(weishtNetWght1);//退货的净重
                cWeightSheets2.setWeishtMoney(multiply);
                cWeightSheets2.setWeishtPrice(cWeightSheets.getWeishtPrice());//退货的价格等于原来的价格
                cWeightSheets2.setWeishtSheetno(cWeightSheets.getWeishtSheetno() + "TH");//退货的磅单号为原来的磅单号+TH
                cWeightSheets2.setWeishtIccardno(cWeightSheets.getWeishtIccardno());//退货的卡号等于原来的卡号
                cWeightSheets2.setWeishtProduct(cWeightSheets.getWeishtProduct());//退货的品种等于原来的品种
                cWeightSheets2.setWeishtCo(cWeightSheets.getWeishtCo());//退货的客户等于原来的客户
                cWeightSheets2.setWeishtChiCo(cWeightSheets.getWeishtChiCo());//退货的子客户等于原来的子客户
                cWeightSheets2.setWeishtCoSupply(cWeightSheets.getWeishtCoSupply());//退货的供应商等于原来的供应商
                cWeightSheets2.setWeishtCoSupplyChi(cWeightSheets.getWeishtCoSupplyChi());//退货的子供应商等于原来的子供应商
                cWeightSheets2.setWeishtEnterTm(cWeightSheets.getWeishtEnterTm());
                cWeightSheets2.setWeishtOutTm(cWeightSheets.getWeishtOutTm());
                cWeightSheets2.setWeishtEmptyTm(cWeightSheets.getWeishtEmptyTm());
                cWeightSheets2.setWeishtFullTm(cWeightSheets.getWeishtFullTm());
                cWeightSheets2.setWeishtLoadTm(cWeightSheets.getWeishtLoadTm());
                cWeightSheets2.setWeishtLoadEndTm(cWeightSheets.getWeishtLoadEndTm());
                cWeightSheets2.setWeishtOperator(cWeightSheets.getWeishtOperator());
                cWeightSheets2.setWeishtAshgateId(cWeightSheets.getWeishtAshgateId());
                cWeightSheets2.setWeishtRemark(cWeightSheets.getWeishtRemark());
                cWeightSheets2.setWeishtBacked(true);
                cWeightSheets2.setWeishtDeleted(0);
                cWeightSheets2.setDownedID1(0);
                cWeightSheets2.setDataFrom(plantId);
                cWeightSheets2.setWeishtTranMode(cWeightSheets.getWeishtTranMode());
                cWeightSheets2.setWeishtIccardtype(cWeightSheets.getWeishtIccardtype());
                cWeightSheets2.setWeishtTruckSn(cWeightSheets.getWeishtTruckSn());
                weightSheetsService.save(cWeightSheets2);

                //再换货
                BigDecimal pdtinfPrice = cProductsInfo1.getPdtinfPrice();//换货的价格
                BigDecimal weishtNetWght = cWeightSheets.getWeishtNetWght();//原来的净重
                CWeightSheets cWeightSheets4 = new CWeightSheets();
                cWeightSheets4.setId(cWeightSheets.getWeishtSheetno() + "HH");
                cWeightSheets4.setWeishtBacked(true);
                cWeightSheets4.setWeishtYearSn(cWeightSheets.getWeishtYearSn());
                cWeightSheets4.setWeishtTruckno(cWeightSheets.getWeishtTruckno());
                cWeightSheets4.setWeishtGrossWght(cWeightSheets.getWeishtGrossWght());//换货的毛重等于原来的毛重
                cWeightSheets4.setWeishtTare(cWeightSheets.getWeishtTare());//换货的皮重等于0
                cWeightSheets4.setWeishtNetWght(cWeightSheets.getWeishtNetWght());//换货的净重等于原来的净重
                cWeightSheets4.setWeishtProduct(cProductsInfo1.getPdtinfPdt());
                cWeightSheets4.setWeishtPrice(pdtinfPrice);//单价
                cWeightSheets4.setWeishtMoney(weishtNetWght.multiply(pdtinfPrice));
                cWeightSheets4.setWeishtSheetno(cWeightSheets.getWeishtSheetno() + "HH");
                cWeightSheets4.setWeishtIccardno(cWeightSheets.getWeishtIccardno());//退货的卡号等于原来的卡号
                cWeightSheets4.setWeishtCo(cWeightSheets.getWeishtCo());//退货的客户等于原来的客户
                cWeightSheets4.setWeishtChiCo(cWeightSheets.getWeishtChiCo());//退货的子客户等于原来的子客户
                cWeightSheets4.setWeishtCoSupply(cWeightSheets.getWeishtCoSupply());//退货的供应商等于原来的供应商
                cWeightSheets4.setWeishtCoSupplyChi(cWeightSheets.getWeishtCoSupplyChi());//退货的子供应商等于原来的子供应商
                cWeightSheets4.setWeishtEnterTm(cWeightSheets.getWeishtEnterTm());
                cWeightSheets4.setWeishtOutTm(cWeightSheets.getWeishtOutTm());
                cWeightSheets4.setWeishtEmptyTm(cWeightSheets.getWeishtEmptyTm());
                cWeightSheets4.setWeishtFullTm(cWeightSheets.getWeishtFullTm());
                cWeightSheets4.setWeishtLoadTm(cWeightSheets.getWeishtLoadTm());
                cWeightSheets4.setWeishtLoadEndTm(cWeightSheets.getWeishtLoadEndTm());
                cWeightSheets4.setWeishtOperator(cWeightSheets.getWeishtOperator());
                cWeightSheets4.setWeishtAshgateId(cWeightSheets.getWeishtAshgateId());//--------------------------------------------------------------------------
                cWeightSheets4.setWeishtRemark(cProductsInfo1.getPdtinfPdt());
                cWeightSheets4.setWeishtDeleted(0);
                cWeightSheets2.setDownedID1(0);
                cWeightSheets4.setDataFrom(plantId);
                cWeightSheets4.setWeishtTranMode(cWeightSheets.getWeishtTranMode());
                cWeightSheets4.setWeishtIccardtype(cWeightSheets.getWeishtIccardtype());
                cWeightSheets4.setWeishtTruckSn(cWeightSheets.getWeishtTruckSn());
                weightSheetsService.save(cWeightSheets4);


                String weishtCoSupply1 = cWeightSheets.getWeishtCoSupply();
                QueryWrapper<CCompanys> queryWrapper6 = new QueryWrapper<>();
                queryWrapper6.eq("CPY_CO", weishtCoSupply1);
                CCompanys one = companysService.getOne(queryWrapper6);
                String cpyId = String.valueOf(one.getCpyId());
                QueryWrapper<COrderDetail> queryWrapper7 = new QueryWrapper<>();
                queryWrapper7.eq("ORDETAIL_CO", cWeightSheets.getWeishtCo());
                queryWrapper7.eq("ORDETAIL_CHICO", cWeightSheets.getWeishtChiCo());
                queryWrapper7.eq("ORDETAIL_DELETED", 0);
                queryWrapper7.eq("ORDETAIL_SUB_ID", cpyId);
                COrderDetail cOrderDetail = orderDetailService.getOne(queryWrapper7);
//                cOrderDetail.setOrdetailRemainNum((cOrderDetail.getOrdetailRemainNum().subtract(cWeightSheets2.getWeishtMoney())).add(cWeightSheets4.getWeishtMoney()));
//                cOrderDetail.setDownedID1(0);
//                orderDetailService.updateById(cOrderDetail);

                String cOrderDetailId = cOrderDetail.getId();

                UpdateWrapper<COrderDetail> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("ID", cOrderDetail.getId());
                updateWrapper.set("DownedID1", 0);
                orderDetailService.update(updateWrapper);
                orderDetailMapper.updateOrderDetailForPdtReturnOrExchange2(cWeightSheets2.getWeishtMoney(), cWeightSheets4.getWeishtMoney(), cOrderDetailId);

                sysLogBu.logRecord("单据换货", sysUser.getTrueName(), "换货了" + "磅单为" + weishtSheetNo + "的磅单" + "理由是:" + reason, plantId);
                return SzResult.Success();
            }
        } else if (inOrOut == 1) {//进货类1
            //进货类的退货
            if (ReturnOrExchange == 1) {//退货
                //查询该磅单是否已经退货
                QueryWrapper<CWeightSheets> queryWrapperTH = new QueryWrapper<>();
                String a = weishtSheetNo + "TH";
                queryWrapperTH.eq("WEISHT_SHEETNO", a);
                queryWrapperTH.eq("WEISHT_DELETED", 0);
                CWeightSheets one = weightSheetsService.getOne(queryWrapperTH);
                if (one != null) {
                    return SzResult.error("该磅单已经退货");
                }
                if (cWeightSheets.getWeishtSheetno().contains("TH")) {
                    return SzResult.error("该磅单为退货单，不能再次退货");
                }
                CWeightSheets cWeightSheets1 = new CWeightSheets();
                cWeightSheets1.setWeishtYearSn(cWeightSheets.getWeishtYearSn());
                cWeightSheets1.setWeishtTruckno(cWeightSheets.getWeishtTruckno());//退货的车号等于原来的车号
                cWeightSheets1.setWeishtGrossWght(weishtNetWght1);//退货的毛重等于原来的净重
                cWeightSheets1.setWeishtTare(BigDecimal.ZERO);//退货的皮重为0
                cWeightSheets1.setWeishtNetWght(weishtNetWght1);//退货的净重等于原来的净重
                cWeightSheets1.setWeishtPrice(cWeightSheets.getWeishtPrice());//退货的价格等于原来的价格
                cWeightSheets1.setWeishtSheetno(cWeightSheets.getWeishtSheetno() + "TH");//退货的磅单号为原来的磅单号+TH
                cWeightSheets1.setWeishtIccardno(cWeightSheets.getWeishtIccardno());//退货的卡号等于原来的卡号
                cWeightSheets1.setWeishtProduct(cWeightSheets.getWeishtProduct());//退货的品种等于原来的品种
                cWeightSheets1.setWeishtCo(cWeightSheets.getWeishtCo());//退货的客户等于原来的客户
                cWeightSheets1.setWeishtChiCo(cWeightSheets.getWeishtChiCo());//退货的子客户等于原来的子客户
                cWeightSheets1.setWeishtCoSupply(cWeightSheets.getWeishtCoSupply());//退货的供应商等于原来的供应商
                cWeightSheets1.setWeishtCoSupplyChi(cWeightSheets.getWeishtCoSupplyChi());//退货的子供应商等于原来的子供应商
                cWeightSheets1.setWeishtEnterTm(cWeightSheets.getWeishtEnterTm());
                cWeightSheets1.setWeishtOutTm(cWeightSheets.getWeishtOutTm());
                cWeightSheets1.setWeishtEmptyTm(cWeightSheets.getWeishtEmptyTm());
                cWeightSheets1.setWeishtFullTm(cWeightSheets.getWeishtFullTm());
                cWeightSheets1.setWeishtLoadTm(cWeightSheets.getWeishtLoadTm());
                cWeightSheets1.setWeishtLoadEndTm(cWeightSheets.getWeishtLoadEndTm());
                cWeightSheets1.setWeishtOperator(cWeightSheets.getWeishtOperator());
                cWeightSheets1.setWeishtAshgateId(cWeightSheets.getWeishtAshgateId());
                cWeightSheets1.setWeishtRemark(cWeightSheets.getWeishtRemark());
                cWeightSheets1.setWeishtDeleted(0);
                cWeightSheets1.setDataFrom(plantId);
                cWeightSheets1.setWeishtTranMode(cWeightSheets.getWeishtTranMode());
                cWeightSheets1.setWeishtIccardtype(cWeightSheets.getWeishtIccardtype());
                cWeightSheets1.setWeishtTruckSn(cWeightSheets.getWeishtTruckSn());
                weightSheetsService.save(cWeightSheets1);
                sysLogBu.logRecord("单据退货", sysUser.getTrueName(), "退货了" + "磅单为" + weishtSheetNo + "的磅单" + "理由是:" + reason, plantId);
            } else {
                if (exchangePdtStockcls == 0) {
                    return SzResult.error("该品种不是进货类货物，不可换货");
                }
                //换货  exchangePdt(换货的品种)
                QueryWrapper<CWeightSheets> queryWrapperHH = new QueryWrapper<>();
                String a = weishtSheetNo + "HH";
                queryWrapperHH.eq("WEISHT_SHEETNO", a);
                queryWrapperHH.eq("WEISHT_DELETED", 0);
                CWeightSheets cWeightSheetsHH = weightSheetsService.getOne(queryWrapperHH);
                if (cWeightSheetsHH != null) {
                    return SzResult.error("该磅单已经换货");
                }
                if (cWeightSheets.getWeishtSheetno().contains("TH")) {
                    return SzResult.error("该磅单为退货单，不能再次换货");
                }
                QueryWrapper<CProductsInfo> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("PDTINF_ID", exchangePdtId);
                queryWrapper3.eq("PDTINF_DELETED", 0);
                queryWrapper3.ne("PDTINF_PDT", weishtProduct);
                queryWrapper3.eq("DATA_FROM", plantId);
                CProductsInfo cProductsInfo1 = productsInfoService.getOne(queryWrapper3);//换货的品种
                if (cProductsInfo1.getPdtinfStockcls() == 1) {
                    return SzResult.error("该品种不是进货类货物，不可换货");
                }
                //进行换货
                BigDecimal pdtinfPrice = cProductsInfo1.getPdtinfPrice();//换货品种的价格
                BigDecimal weishtPrice = cWeightSheets.getWeishtPrice();//原来的品种的价格
                BigDecimal weishtNetWght = cWeightSheets.getWeishtNetWght();//原来的净重
                BigDecimal multiply1 = weishtNetWght.multiply(pdtinfPrice);
                multiply1 = multiply1.multiply(BigDecimal.valueOf(-1));
                CWeightSheets cWeightSheets2 = new CWeightSheets();
                cWeightSheets2.setId(cWeightSheets.getWeishtSheetno() + "HH");
                cWeightSheets2.setWeishtBacked(true);
                cWeightSheets2.setWeishtYearSn(cWeightSheets.getWeishtYearSn());
                cWeightSheets2.setWeishtTruckno(cWeightSheets.getWeishtTruckno());
                cWeightSheets2.setWeishtTare(BigDecimal.valueOf(0));//皮重
                cWeightSheets2.setWeishtGrossWght(weishtNetWght1);//毛重
                cWeightSheets2.setWeishtNetWght(weishtNetWght1);//净重
                cWeightSheets2.setWeishtProduct(cProductsInfo1.getPdtinfPdt());
                cWeightSheets2.setWeishtPrice(pdtinfPrice);//单价
                cWeightSheets2.setWeishtMoney(multiply1);//金额
                cWeightSheets2.setWeishtSheetno(cWeightSheets.getWeishtSheetno() + "HH");
                cWeightSheets2.setWeishtIccardno(cWeightSheets.getWeishtIccardno());//退货的卡号等于原来的卡号
                cWeightSheets2.setWeishtCo(cWeightSheets.getWeishtCo());//退货的客户等于原来的客户
                cWeightSheets2.setWeishtChiCo(cWeightSheets.getWeishtChiCo());//退货的子客户等于原来的子客户
                cWeightSheets2.setWeishtCoSupply(cWeightSheets.getWeishtCoSupply());//退货的供应商等于原来的供应商
                cWeightSheets2.setWeishtCoSupplyChi(cWeightSheets.getWeishtCoSupplyChi());//退货的子供应商等于原来的子供应商
                cWeightSheets2.setWeishtEnterTm(cWeightSheets.getWeishtEnterTm());
                cWeightSheets2.setWeishtOutTm(cWeightSheets.getWeishtOutTm());
                cWeightSheets2.setWeishtEmptyTm(cWeightSheets.getWeishtEmptyTm());
                cWeightSheets2.setWeishtFullTm(cWeightSheets.getWeishtFullTm());
                cWeightSheets2.setWeishtLoadTm(cWeightSheets.getWeishtLoadTm());
                cWeightSheets2.setWeishtLoadEndTm(cWeightSheets.getWeishtLoadEndTm());
                cWeightSheets2.setWeishtOperator(cWeightSheets.getWeishtOperator());
                cWeightSheets2.setWeishtAshgateId(cWeightSheets.getWeishtAshgateId());
                cWeightSheets2.setWeishtRemark(cProductsInfo1.getPdtinfPdt());
                cWeightSheets2.setWeishtDeleted(0);
                cWeightSheets2.setDataFrom(plantId);
                cWeightSheets2.setWeishtTranMode(cWeightSheets.getWeishtTranMode());
                cWeightSheets2.setWeishtIccardtype(cWeightSheets.getWeishtIccardtype());
                cWeightSheets2.setWeishtTruckSn(cWeightSheets.getWeishtTruckSn());
                weightSheetsService.save(cWeightSheets2);
                sysLogBu.logRecord("单据换货", sysUser.getTrueName(), "换货了" + "磅单为" + weishtSheetNo + "的磅单" + "理由是:" + reason, plantId);
            }
        }
        return SzResult.Success();
    }

    /**
     * 模板导出
     */


    public SzResult templateExport(String id, String templateId, String token) throws Exception {
//f847087c4904deb43bf03fece7b9c83d
        // String templateFileName = "D:\\IdeaProject\\intranet-web-group\\excelTemplates\\" + templateId + ".xlsx";


        QueryWrapper<TExcelTemplates> queryWrapperExcelTemplate = new QueryWrapper<>();
        queryWrapperExcelTemplate.eq("ID", templateId);
        TExcelTemplates one = excelTemplatesService.getOne(queryWrapperExcelTemplate);
        String excelPath = one.getExcelPath();
        String templateFileName = excelPath + "\\" + templateId + ".xlsx";
        QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        CWeightSheets cWeightSheets1 = weightSheetsService.getOne(queryWrapper);
        String weishtSheetno = cWeightSheets1.getWeishtSheetno();
        String fileName = "D:\\templete\\" + weishtSheetno + ".xlsx";
        Map<String, Object> dataMap = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        String string = now.toString().replace("T", " ");
        String time = string + "           " + "单号: " + weishtSheetno;
        String weishtCoSupply = cWeightSheets1.getWeishtCoSupply();
        String weishtCoSupplyChi = cWeightSheets1.getWeishtCoSupplyChi();
        String supplyCo = weishtCoSupply + weishtCoSupplyChi;
        String co = cWeightSheets1.getWeishtCo();
        String coChi = cWeightSheets1.getWeishtChiCo();
        String co1 = co + coChi;
        String icCard = cWeightSheets1.getWeishtIccardno();
        String truckNo = cWeightSheets1.getWeishtTruckno();
        String transCo = cWeightSheets1.getWeishtCoTran();
        String transCoChi = cWeightSheets1.getWeishtChiCoTran();
        String transCo1 = transCo + transCoChi;
        if (transCo == null) {
            transCo1 = null;
        }
        LocalDateTime enterTime = cWeightSheets1.getWeishtEnterTm();
        String a = "";
        if (enterTime != null) {
            a = enterTime.toString().replace("T", " ");
        }
        String inTime = a;

        String outTime = cWeightSheets1.getWeishtOutTm().toString().replace("T", " ");

        String product = cWeightSheets1.getWeishtProduct();
        String tare = cWeightSheets1.getWeishtTare().toString();
        String gross = cWeightSheets1.getWeishtGrossWght().toString();
        String net = cWeightSheets1.getWeishtNetWght().toString();
        String money = cWeightSheets1.getWeishtMoney().toString();
        String weishtOperator = cWeightSheets1.getWeishtOperator();
        String remark = cWeightSheets1.getWeishtRemark();
        String title = supplyCo + "物资称重单";
        dataMap.put("title", title);
        dataMap.put("time", time);
        dataMap.put("supplyCo", supplyCo);
        dataMap.put("co", co1);
        dataMap.put("icCard", icCard);
        dataMap.put("truckNo", truckNo);
        dataMap.put("transCo", transCo1);
        dataMap.put("enterTime", inTime);
        dataMap.put("outTime", outTime);
        dataMap.put("product", product);
        dataMap.put("tare", tare);
        dataMap.put("gross", gross);
        dataMap.put("net", net);
        dataMap.put("money", money);
        dataMap.put("remark1", remark);
        dataMap.put("weightMan", weishtOperator);
        dataMap.put("trueProduct", product);

        EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(dataMap);
        return SzResult.Success();
    }

    @Transactional
    //磅单高级操作
    public SzResult weightSheetAdvanced(String id, String truckNo, String product, String tranChiCo, String weishtGrossWght, String weishtTare, String weishtNetWght, String weishtMoney,
                                        String supplyCo, String supplyChiCo, String co, String chiCo, String weishtEmptyTm, String weishtFullTm, String weishtLoadTm, String weishtLoadEndTm, String weishtEnterTm, String weishtOutTm, String token, String plantId) throws Exception {
        //  String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("WEISHT_DELETED", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        CWeightSheets cWeightSheets = weightSheetsService.getOne(queryWrapper);
        String originalWeishtCo = cWeightSheets.getWeishtCo();
        String originalWeishtChiCo = cWeightSheets.getWeishtChiCo();
        String originalWeishtCoSupply = cWeightSheets.getWeishtCoSupply();
        String originalWeishtCoSupplyChi = cWeightSheets.getWeishtCoSupplyChi();
        String originalWeishtProduct = cWeightSheets.getWeishtProduct();
        BigDecimal weishtGrossWght1;
        BigDecimal weishtTare1;
        try {
            weishtGrossWght1 = new BigDecimal(weishtGrossWght);
            weishtTare1 = new BigDecimal(weishtTare);
        } catch (NumberFormatException e) {
            // 如果输入的字符串无法转换为数字，则抛出异常或采取其他措施
            throw new IllegalArgumentException("无效的重量值", e);
        }

        weishtNetWght = String.valueOf(weishtGrossWght1.subtract(weishtTare1));
        BigDecimal weishtNetWght1 = new BigDecimal(weishtNetWght);
        BigDecimal weishtPrice = cWeightSheets.getWeishtPrice();

// 计算净重乘以价格
        BigDecimal originalWeishtMoney = weishtNetWght1.multiply(weishtPrice).setScale(2, RoundingMode.HALF_UP);
//找到修改后的新供货单位
        QueryWrapper<CCompanys> companysQueryWrapper2 = new QueryWrapper<>();
        companysQueryWrapper2.eq("CPY_CO", supplyCo);
        companysQueryWrapper2.eq("CPY_CHICO", supplyChiCo);
        companysQueryWrapper2.eq("DATA_FROM", plantId);
        companysQueryWrapper2.eq("CPY_DELETED", 0);
        CCompanys companys1 = companysService.getOne(companysQueryWrapper2);

        QueryWrapper<CCompanys> companysQueryWrapper = new QueryWrapper<>();
        companysQueryWrapper.eq("CPY_CO", originalWeishtCoSupply);
        companysQueryWrapper.eq("CPY_CHICO", originalWeishtCoSupplyChi);
        companysQueryWrapper.eq("DATA_FROM", plantId);
        companysQueryWrapper.eq("CPY_DELETED", 0);
        CCompanys companys = companysService.getOne(companysQueryWrapper);
        String originalCpyId = companys.getId();
        if (truckNo != null) {
            cWeightSheets.setWeishtTruckno(truckNo);
        }

        if (product != null) {
            //判断该品种是否授权给该单位(收货单位)
            if (co != null && chiCo != null) {
                QueryWrapper<CPdtsAuth> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("PDTSAUTH_PDT", product);
                queryWrapper2.eq("PDTSAUTH_CO", co);
                queryWrapper2.eq("PDTSAUTH_CHICO", chiCo);
                queryWrapper2.eq("PDTSAUTH_DELETED", 0);
                CPdtsAuth one1 = pdtsAuthService.getOne(queryWrapper2);
                if (one1 == null) {
                    return SzResult.error("该品种未授权给该单位");
                } else {
                    cWeightSheets.setWeishtProduct(product);
                }
            } else {
                String weishtCo = cWeightSheets.getWeishtCo();
                String weishtChiCo = cWeightSheets.getWeishtChiCo();
                QueryWrapper<CPdtsAuth> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("PDTSAUTH_PDT", product);
                queryWrapper2.eq("PDTSAUTH_CO", weishtCo);
                queryWrapper2.eq("PDTSAUTH_CHICO", weishtChiCo);
                queryWrapper2.eq("PDTSAUTH_DELETED", 0);
                CPdtsAuth one1 = pdtsAuthService.getOne(queryWrapper2);
                if (one1 == null) {
                    return SzResult.error("该品种未授权给该单位");
                } else {
                    cWeightSheets.setWeishtProduct(product);
                }
            }
        }
        //修改单位,如果供货单位或者收货单位不为空时  supplyCo, supplyChiCi, co, chiCo
        if (co != null && chiCo != null) {//收货单位不为空时
            String weishtProduct = cWeightSheets.getWeishtProduct();
            //判断该品种是否授权给这个要修改成的收货单位
            QueryWrapper<CPdtsAuth> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("PDTSAUTH_PDT", weishtProduct);
            queryWrapper2.eq("PDTSAUTH_CO", co);
            queryWrapper2.eq("PDTSAUTH_CHICO", chiCo);
            queryWrapper2.eq("PDTSAUTH_DELETED", 0);
            CPdtsAuth one1 = pdtsAuthService.getOne(queryWrapper2);
            if (one1 == null) {
                return SzResult.error("该品种未授权给该单位");
            } else {
                cWeightSheets.setWeishtCo(co);
                cWeightSheets.setWeishtChiCo(chiCo);
            }
        }

//到这里时，单位已经修改完毕
        if (weishtGrossWght != null) {
            weishtGrossWght1 = new BigDecimal(weishtGrossWght);
            cWeightSheets.setWeishtGrossWght(weishtGrossWght1);//毛重
        }

        if (weishtTare != null) {
            weishtTare1 = new BigDecimal(weishtTare);
            cWeightSheets.setWeishtTare(weishtTare1);//皮重
        }
        if (weishtNetWght != null) {
            weishtNetWght1 = new BigDecimal(weishtNetWght);
            cWeightSheets.setWeishtNetWght(weishtNetWght1);//净重
        }

        String weishtProduct = cWeightSheets.getWeishtProduct();//修改后的品种
        //用新品种的价格
        QueryWrapper<CProductsInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("PDTINF_PDT", weishtProduct);
        queryWrapper1.eq("PDTINF_DELETED", 0);
        CProductsInfo one = productsInfoService.getOne(queryWrapper1);

////        BigDecimal pdtinfPrice = one.getPdtinfPrice();
//        BigDecimal weishtMoney1;
//        if (cWeightSheets.getWeishtNetWght() != null) {
//            weishtMoney1 = cWeightSheets.getWeishtNetWght().multiply(pdtinfPrice);

//        }
        //算出钱,如果变了,就改余额,如果没变,就不改，//        金额还有个问题就是如果供货单位变了就要还回原单位，扣除新单位
        if (Objects.equals(originalWeishtCoSupply, supplyCo)) {
            if (!Objects.equals(originalWeishtMoney, cWeightSheets.getWeishtMoney())) {//变了
//            然后判断是大于原款还是小于原款，大于原款就是减，小于原款就是加
                // 计算差额
                BigDecimal difference = originalWeishtMoney.subtract(cWeightSheets.getWeishtMoney());
                //找到原来的余额,扣除掉
                QueryWrapper<COrderDetail> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("ORDETAIL_CO", originalWeishtCo);
                queryWrapper2.eq("ORDETAIL_CHICO", originalWeishtChiCo);
                queryWrapper2.eq("ORDETAIL_SUB_ID", originalCpyId);
                queryWrapper2.eq("ORDETAIL_DELETED", 0);
                queryWrapper2.eq("DATA_FROM", plantId);
                COrderDetail one1 = orderDetailService.getOne(queryWrapper2);
//            one1.setOrdetailRemainNum(one1.getOrdetailRemainNum().subtract(originalWeishtMoney));//对应的账户减去了原来的钱
//            orderDetailService.updateById(one1);difference
                orderDetailMapper.updateOrderDetailForWeightSheetAdvanced(difference, one1.getId());

                //根据新的品种找到该品种的id
//            QueryWrapper<CProductsInfo> queryWrapper3 = new QueryWrapper<>();
//            queryWrapper3.eq("PDTINF_PDT", weishtProduct);
//            queryWrapper3.eq("PDTINF_DELETED", 0);
//            CProductsInfo one2 = productsInfoService.getOne(queryWrapper3);
//            String newPdtId = String.valueOf(one2.getPdtinfId());
                //再根据新的单位和品种找到应该充值到的账户,如果没有就新建
                QueryWrapper<COrderDetail> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("ORDETAIL_CO", co);
                queryWrapper4.eq("ORDETAIL_CHICO", chiCo);
                queryWrapper4.eq("ORDETAIL_SUB_ID", originalCpyId);
                queryWrapper4.eq("ORDETAIL_DELETED", 0);
                queryWrapper4.eq("DATA_FROM", plantId);
                COrderDetail one3 = orderDetailService.getOne(queryWrapper4);
                if (one3 == null && originalWeishtMoney.compareTo(BigDecimal.valueOf(0)) > 0) {//没有这个账户,新建
                    COrderDetail cOrderDetail = new COrderDetail();
                    cOrderDetail.setOrdetailCo(co);
                    cOrderDetail.setOrdetailChico(chiCo);
                    cOrderDetail.setOrdetailSubId(originalCpyId);

//                这里考虑的扣款应该是初始化负的余额，如果扣负的余额那就没有必要了
                    cOrderDetail.setOrdetailRemainNum(originalWeishtMoney.negate());
                    cOrderDetail.setOrdetailDeleted(0);
                    cOrderDetail.setDataFrom(plantId);
                    orderDetailService.save(cOrderDetail);
                }
            }
        } else {
            // 计算差额
            //������的余额��回来
            QueryWrapper<COrderDetail> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ORDETAIL_CO", originalWeishtCo);
            queryWrapper2.eq("ORDETAIL_CHICO", originalWeishtChiCo);
            queryWrapper2.eq("ORDETAIL_SUB_ID", originalCpyId);
            queryWrapper2.eq("ORDETAIL_DELETED", 0);
            queryWrapper2.eq("DATA_FROM", plantId);
            COrderDetail one1 = orderDetailService.getOne(queryWrapper2);
//        @Select("UPDATE c_order_detail\n" +
//        "SET ORDETAIL_REMAIN_NUM = ORDETAIL_REMAIN_NUM + #{multiply}\n" +
//        "WHERE id = #{id}")
//    void updateOrderDetailForWeightSheetAdvanced2(BigDecimal multiply, String id);
//        退回原账户
            orderDetailMapper.updateOrderDetailForWeightSheetAdvanced2(cWeightSheets.getWeishtMoney(), one1.getId());
//        减掉新户头的钱
            QueryWrapper<COrderDetail> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.eq("ORDETAIL_CO", co);
            queryWrapper4.eq("ORDETAIL_CHICO", chiCo);
            queryWrapper4.eq("ORDETAIL_SUB_ID", companys1.getId());
            queryWrapper4.eq("ORDETAIL_DELETED", 0);
            queryWrapper4.eq("DATA_FROM", plantId);
            COrderDetail one3 = orderDetailService.getOne(queryWrapper4);
            if (one3 == null) {
                COrderDetail cOrderDetail = new COrderDetail();
                cOrderDetail.setOrdetailCo(co);
                cOrderDetail.setOrdetailChico(chiCo);
                cOrderDetail.setOrdetailSubId(companys1.getId());
                cOrderDetail.setOrdetailRemainNum(cWeightSheets.getWeishtMoney().negate());
                cOrderDetail.setOrdetailDeleted(0);
                cOrderDetail.setDataFrom(plantId);
                orderDetailService.save(cOrderDetail);
            } else {
                orderDetailMapper.updateOrderDetailForWeightSheetAdvanced(originalWeishtMoney, one3.getId());
            }
        }

//    如果改变收货单位了也要改变余额

        // 修改了收货单位后重新扣款的逻辑
        if (!originalWeishtCo.equals(co) || !originalWeishtChiCo.equals(chiCo)) {
            // 退还原收货单位的钱
            QueryWrapper<COrderDetail> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ORDETAIL_CO", originalWeishtCo);
            queryWrapper2.eq("ORDETAIL_CHICO", originalWeishtChiCo);
            queryWrapper2.eq("ORDETAIL_SUB_ID", originalCpyId);
            queryWrapper2.eq("ORDETAIL_DELETED", 0);
            queryWrapper2.eq("DATA_FROM", plantId);
            COrderDetail originalOrderDetail = orderDetailService.getOne(queryWrapper2);
            if (originalOrderDetail != null) {
                orderDetailMapper.updateOrderDetailForWeightSheetAdvanced2(originalWeishtMoney, originalOrderDetail.getId());
            }

            // 扣除新收货单位的钱
            QueryWrapper<COrderDetail> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.eq("ORDETAIL_CO", co);
            queryWrapper4.eq("ORDETAIL_CHICO", chiCo);
            queryWrapper4.eq("ORDETAIL_SUB_ID", companys1.getId());
            queryWrapper4.eq("ORDETAIL_DELETED", 0);
            queryWrapper4.eq("DATA_FROM", plantId);
            COrderDetail newOrderDetail = orderDetailService.getOne(queryWrapper4);
            if (newOrderDetail == null) {
                // 创建新的订单详情记录
                newOrderDetail = new COrderDetail();
                newOrderDetail.setOrdetailCo(co);
                newOrderDetail.setOrdetailChico(chiCo);
                newOrderDetail.setOrdetailSubId(companys1.getId());
                newOrderDetail.setOrdetailRemainNum(BigDecimal.ZERO);
                newOrderDetail.setOrdetailDeleted(0);
                newOrderDetail.setDataFrom(plantId);
                orderDetailService.save(newOrderDetail);
                orderDetailMapper.updateOrderDetailForWeightSheetAdvanced(originalWeishtMoney, newOrderDetail.getId());
            } else {
                orderDetailMapper.updateOrderDetailForWeightSheetAdvanced(originalWeishtMoney, newOrderDetail.getId());
            }
        }
//        到此改变磅单余额
        if (supplyCo != null && supplyChiCo != null) {
            cWeightSheets.setWeishtCoSupply(supplyCo);
            cWeightSheets.setWeishtCoSupplyChi(supplyChiCo);
        }
        cWeightSheets.setWeishtMoney(originalWeishtMoney);
        if (weishtEmptyTm != null && !weishtEmptyTm.equals("")) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]");
            LocalDateTime localDateTime = LocalDateTime.parse(weishtEmptyTm, formatter);
            cWeightSheets.setWeishtEmptyTm(localDateTime);
        }
        if (weishtFullTm != null && !weishtFullTm.equals("")) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]");
            LocalDateTime localDateTime = LocalDateTime.parse(weishtFullTm, formatter);
            cWeightSheets.setWeishtFullTm(localDateTime);
        }
        if (weishtLoadTm != null && !weishtLoadTm.equals("")) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]");
            LocalDateTime localDateTime = LocalDateTime.parse(weishtLoadTm, formatter);
            cWeightSheets.setWeishtLoadTm(localDateTime);
        }
        if (weishtLoadEndTm != null && !weishtLoadEndTm.equals("")) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]");
            LocalDateTime localDateTime = LocalDateTime.parse(weishtLoadEndTm, formatter);
            cWeightSheets.setWeishtLoadEndTm(localDateTime);
        }
        if (weishtEnterTm != null && !weishtEnterTm.equals("")) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]");
            LocalDateTime localDateTime = LocalDateTime.parse(weishtEnterTm, formatter);
            cWeightSheets.setWeishtEnterTm(localDateTime);
        }
        if (weishtOutTm != null && !weishtOutTm.equals("")) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]");
            LocalDateTime localDateTime = LocalDateTime.parse(weishtOutTm, formatter);
            cWeightSheets.setWeishtOutTm(localDateTime);
        }
        cWeightSheets.setDownedID1(0);
        weightSheetsService.updateById(cWeightSheets);
        return SzResult.Success();
    }


    /**
     * 磅单打印
     */
    public SzResult weightSheetPrint(List<String> weightSheetIdList, String token, String plantId) throws Exception {
        int size = weightSheetIdList.size();
        if (size == 0) {
            return SzResult.error("请选择要打印的磅单");
        }
        List<WeighingSheetVo> weightSheetList = new ArrayList<>();
        for (String s : weightSheetIdList) {
            WeighingSheetVo weighingSheetVo = new WeighingSheetVo();
            QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ID", s);
            queryWrapper.eq("WEISHT_DELETED", 0);
            queryWrapper.eq(plantId != null && !plantId.isEmpty(), "DATA_FROM", plantId);
            CWeightSheets one = weightSheetsService.getOne(queryWrapper);
            String s1 = one.getWeishtCoSupply() + "." + one.getWeishtCoSupplyChi();
            weighingSheetVo.setTitle(s1 + "磅单打印单");
            weighingSheetVo.setSupplyCo(s1);
            weighingSheetVo.setCo(one.getWeishtCo() + "." + one.getWeishtChiCo());
            weighingSheetVo.setTransCo(one.getWeishtCoTran() + "." + one.getWeishtChiCoTran());
            weighingSheetVo.setIcCard(one.getWeishtIccardno());
            weighingSheetVo.setTruckNo(one.getWeishtTruckno());
            weighingSheetVo.setEnterTime(one.getWeishtEnterTm().toString().replace("T", " "));
            weighingSheetVo.setOutTime(one.getWeishtOutTm().toString().replace("T", " "));
            weighingSheetVo.setProduct(one.getWeishtProduct());
            weighingSheetVo.setTare(one.getWeishtTare().toString());
            weighingSheetVo.setGross(one.getWeishtGrossWght().toString());
            weighingSheetVo.setNet(one.getWeishtNetWght().toString());
            weighingSheetVo.setMoney(one.getWeishtMoney().toString());
            weighingSheetVo.setRemark1(one.getWeishtRemark());
            weighingSheetVo.setOperator(one.getWeishtOperator());
            weightSheetList.add(weighingSheetVo);
        }
        return SzResult.success(weightSheetList);
    }


    //年度环比报表
    public SzResult yearOnYearReport(Integer year1, Integer year2, String cpyId, String plantId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (cpyId != null && !cpyId.isEmpty()) {
            QueryWrapper<CCompanys> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ID", cpyId);
            queryWrapper.eq("CPY_DELETED", 0);
            queryWrapper.eq("DATA_FROM", plantId);
            CCompanys one = companysService.getOne(queryWrapper);
            map.put("co", one.getCpyCo());
            map.put("chiCo", one.getCpyChico());
        }
        map.put("year1", year1);
        map.put("year2", year2);

        map.put("plantId", plantId);
        List<YearOnYearReportVo> annualMoneyTrendVos = cWeightSheetsMapper.yearOnYearReport(map);
        for (YearOnYearReportVo annualMoneyTrendVo : annualMoneyTrendVos) {

            // annualMoneyTrendVo.getDeliverNum2() == null ? 0 : annualMoneyTrendVo.getDeliverNum2()
            String deliverNum2 = annualMoneyTrendVo.getDeliverNum2() == null ? String.valueOf(0) : annualMoneyTrendVo.getDeliverNum2();
            String deliverNum1 = annualMoneyTrendVo.getDeliverNum1() == null ? String.valueOf(0) : annualMoneyTrendVo.getDeliverNum1();
            String year11 = annualMoneyTrendVo.getYear1();
            String year21 = annualMoneyTrendVo.getYear2();
            double competeLastPeriod1 = 0.00;
            String competeLastPeriod = null;

            if (year1 > year2) {
                competeLastPeriod1 = (Double.parseDouble(deliverNum1) - Double.parseDouble(deliverNum2)) / Double.parseDouble(deliverNum2) * 100;
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                competeLastPeriod = decimalFormat.format(competeLastPeriod1);
            }
            if (year1 < year2) {
                competeLastPeriod1 = (Double.parseDouble(deliverNum2) - Double.parseDouble(deliverNum1)) / Double.parseDouble(deliverNum1) * 100;
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                competeLastPeriod = decimalFormat.format(competeLastPeriod1);
            }

            List<Map<String, String>> list = new ArrayList<>();
            Map map1 = new HashMap<>();
            Map map2 = new HashMap<>();
            Map map3 = new HashMap<>();
            if (!Objects.equals(year11, year21)) {
                map1.put("year", year1);
                map1.put("yearAndDeliverNum", deliverNum1);
                list.add(map1);
                map2.put("year", year2);
                map2.put("yearAndDeliverNum", deliverNum2);
                list.add(map2);
                map3.put("competeLastPeriod", competeLastPeriod == null ? 0 : competeLastPeriod + "%");
                list.add(map3);
            }
            if (Objects.equals(year11, year21)) {
                map1.put("year", year1);
                map1.put("yearAndDeliverNum", deliverNum1);
                list.add(map1);
                map3.put("competeLastPeriod", "0%");
                list.add(map3);
            }
            annualMoneyTrendVo.setYearAndDeliverNum(list);

        }
        return SzResult.success(annualMoneyTrendVos);
    }


    //年度环比报表（按品种）
    public SzResult yearOnYearReportByPdt(Integer year1, Integer year2, String pdtId, String plantId) throws Exception {
//        plantId = "e9f6ed8e091611ec842700163e092c06";
        Map<String, Object> map = new HashMap<>();
        if (pdtId != null && !pdtId.isEmpty()) {
            QueryWrapper<CProductsInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ID", pdtId);
            queryWrapper.eq("PDTINF_DELETED", 0);
            queryWrapper.eq("DATA_FROM", plantId);
            CProductsInfo one = productsInfoService.getOne(queryWrapper);
            map.put("pdt", one.getPdtinfPdt());
        }
        map.put("year1", year1);
        map.put("year2", year2);
        map.put("plantId", plantId);
        List<YearOnYearReportVo> annualMoneyTrendVos = cWeightSheetsMapper.yearOnYearReportByPdt(map);
        for (YearOnYearReportVo annualMoneyTrendVo : annualMoneyTrendVos) {
            String deliverNum2 = annualMoneyTrendVo.getDeliverNum2() == null ? String.valueOf(0) : annualMoneyTrendVo.getDeliverNum2();
            String deliverNum1 = annualMoneyTrendVo.getDeliverNum1() == null ? String.valueOf(0) : annualMoneyTrendVo.getDeliverNum1();
            String year11 = annualMoneyTrendVo.getYear1();
            String year21 = annualMoneyTrendVo.getYear2();
            double competeLastPeriod1 = 0.00;
            String competeLastPeriod = null;

            if (year1 > year2) {

                competeLastPeriod1 = (Double.parseDouble(deliverNum1) - Double.parseDouble(deliverNum2)) / Double.parseDouble(deliverNum2) * 100;
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                competeLastPeriod = decimalFormat.format(competeLastPeriod1);
            }
            if (year1 < year2) {
                competeLastPeriod1 = (Double.parseDouble(deliverNum2) - Double.parseDouble(deliverNum1)) / Double.parseDouble(deliverNum1) * 100;
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                competeLastPeriod = decimalFormat.format(competeLastPeriod1);
            }

            List<Map<String, String>> list = new ArrayList<>();
            Map map1 = new HashMap<>();
            Map map2 = new HashMap<>();
            Map map3 = new HashMap<>();
            if (!Objects.equals(year11, year21)) {
                map1.put("year", year1);
                map1.put("yearAndDeliverNum", deliverNum1);
                list.add(map1);
                map2.put("year", year2);
                map2.put("yearAndDeliverNum", deliverNum2);
                list.add(map2);
                map3.put("competeLastPeriod", competeLastPeriod == null ? 0 : competeLastPeriod + "%");
                list.add(map3);
            }
            if (Objects.equals(year11, year21)) {
                map1.put("year", year1);
                map1.put("yearAndDeliverNum", deliverNum1);
                list.add(map1);
                map3.put("competeLastPeriod", "0%");
                list.add(map3);
            }
            annualMoneyTrendVo.setYearAndDeliverNum(list);

        }
        return SzResult.success(annualMoneyTrendVos);
    }

    //季度环比报表（按公司）  第一季度1月-3月，第二季度4月-6月，第三季度7月-9月，第四季度10月-12月
    public SzResult quarterOnQuarterReport(String quarter1, String quarter2, String cpyId, String plantId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (cpyId != null && !cpyId.isEmpty()) {
            QueryWrapper<CCompanys> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CPY_ID", cpyId);
            queryWrapper.eq("CPY_DELETED", 0);
            queryWrapper.eq("DATA_FROM", plantId);
            CCompanys one = companysService.getOne(queryWrapper);
            map.put("co", one.getCpyCo());
            map.put("chiCo", one.getCpyChico());
        }
        map.put("year1", quarter1);
        map.put("year2", quarter2);
        map.put("plantId", plantId);

//查某一年的某个季度的数据。例如：参数为  2022年第一季度，2023年第四季度


//        List<QuarterOnQuarterReportVo> quarterOnQuarterReportVos = cWeightSheetsMapper.quarterOnQuarterReport(map);
//        for (QuarterOnQuarterReportVo quarterOnQuarterReportVo : quarterOnQuarterReportVos) {
//            String deliverNum2 = quarterOnQuarterReportVo.getDeliverNum2() == null ? String.valueOf(0) : quarterOnQuarterReportVo.getDeliverNum2();
//            String deliverNum1 = quarterOnQuarterReportVo.getDeliverNum1() == null ? String.valueOf(0) : quarterOnQuarterReportVo.getDeliverNum1();
//            String year11 = quarterOnQuarterReportVo.getYear1();
//            String year21 = quarterOnQuarterReportVo.getYear2();
//            double competeLastPeriod1 = 0.00;
//            String competeLastPeriod = null;
//
//            if (Integer.parseInt(year1) > Integer.parseInt(year2)) {
//                competeLastPeriod1 = (Double.parseDouble(deliverNum1) - Double.parseDouble(deliverNum2)) / Double.parseDouble(deliverNum2) * 100;
//                DecimalFormat decimalFormat = new DecimalFormat("#.##");
//                competeLastPeriod = decimalFormat.format(competeLastPeriod1);
//            }
//            if (Integer.parseInt(year1) < Integer.parseInt(year2)) {
//                competeLastPeriod1 = (Double.parseDouble(deliverNum2) - Double.parseDouble(deliverNum1)) / Double.parseDouble(deliverNum1) * 100;
//                DecimalFormat decimalFormat = new DecimalFormat("#.##");
//                competeLastPeriod = decimalFormat.format(competeLastPeriod1);
//            }
//        }
        return SzResult.success(null);
    }

    public SzResult addPipeAshWeightSheet(String weight, String endTime, String plantId) {
        CWeightSheets weightSheet = new CWeightSheets();
        weightSheet.setWeishtFullTm(LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        String date = DateUtil.format(new Date(), "yyyyMMdd");
        QueryWrapper<CWeightSheets> weightSheetsQueryWrapper = new QueryWrapper<>();
        weightSheetsQueryWrapper.likeRight("ID", "GD" + date);
//        weightSheetsQueryWrapper.eq("DATA_FROM",)
        weightSheetsQueryWrapper.orderByDesc("ID");
        List<CWeightSheets> list = weightSheetsService.list(weightSheetsQueryWrapper);
        String dateId = list.size() == 0 ? null : list.get(0).getId();
        if (dateId == null) {
//            setFinanceEnterId是BigDecimal类型的，所以要转换
            weightSheet.setId("GD" + DateUtil.format(new Date(), "yyyyMMdd") + "001");
            weightSheet.setWeishtSheetno("GD" + DateUtil.format(new Date(), "yyyyMMdd") + "001");
        } else {
            //            substring是截取字符串，截取最后三位，也就是001
            String substring = dateId.substring(dateId.length() - 3);
//            substring1是截取前面的20230601
            String substring1 = dateId.substring(0, dateId.length() - 3);
//            substring2是截取的001转换成int类型的1
            int substring2 = Integer.parseInt(substring) + 1;
//            substring3是把1转换成字符串类型的001
            String substring3 = String.format("%03d", substring2);
//            substring4是把20230601和001拼接成20230601001
            String substring4 = substring1 + substring3;
//            substring5是把20230601001转换成BigDecimal类型的20230601001
//                BigDecimal substring5 = new BigDecimal();
            weightSheet.setId(substring4);
            weightSheet.setWeishtSheetno(substring4);
        }
        QueryWrapper<CWeightSheets> weightSheetsWrapper = new QueryWrapper<>();
        weightSheetsWrapper.likeRight("ID", "GD");
        weightSheetsWrapper.eq("WEISHT_DELETED", 0);
        weightSheetsWrapper.orderByDesc("WEISHT_FULL_TM");
        List<CWeightSheets> weightSheets = weightSheetsService.list(weightSheetsWrapper);
        weightSheet.setWeishtGrossWght(new BigDecimal(weight));
        if (weightSheets.size() > 0) {
            weightSheet.setWeishtEmptyTm(weightSheets.get(0).getWeishtFullTm());
            weightSheet.setWeishtTare(weightSheets.get(0).getWeishtGrossWght());
//            weightSheet.setWeishtNetWght(weightSheet.getWeishtGrossWght().subtract(weightSheet.getWeishtTare()));
            weightSheet.setWeishtNetWght(new BigDecimal(weight).subtract(weightSheets.get(0).getWeishtGrossWght()));
        } else {
            weightSheet.setWeishtEmptyTm(LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            weightSheet.setWeishtTare(new BigDecimal(weight));
            weightSheet.setWeishtNetWght(new BigDecimal(0));
        }
        weightSheet.setWeishtCo("邹城市兴企新型建材有限公司");
        weightSheet.setWeishtChiCo("，");
        weightSheet.setWeishtCoSupply("电厂");
        weightSheet.setWeishtCoSupplyChi("，");
        weightSheet.setWeishtProduct("管道灰");
        weightSheet.setWeightSpecialPrice(new BigDecimal(0));
        weightSheet.setWeishtMoney(new BigDecimal(0));
        weightSheet.setWeishtAshgateId(BigDecimal.valueOf(20));
        weightSheet.setWeishtPriceId("100db760390111ef987900ff8a757bed");
        weightSheet.setWeishtPriceType("市场价");
        weightSheet.setWeishtDeduction(new BigDecimal(1));
        weightSheet.setWeishtBacked(true);
        weightSheet.setDataFrom(plantId);
        return SzResult.success(weightSheetsService.save(weightSheet));
    }

    //    //      进货类处理，如果进货类单子有竞价啥的遗留数据就清理掉
    public void clearWeightSheet() {
        QueryWrapper<CWeightSheets> weightSheetsWrapper = new QueryWrapper<>();
//        是进货类
        weightSheetsWrapper.like("WEISHT_PRODUCT",".");
        //有回磅时间
        weightSheetsWrapper.isNotNull("WEISHT_FULL_TM");
        //已经回磅
        weightSheetsWrapper.eq("WEISHT_BACKED", 1);
        //没有被删
        weightSheetsWrapper.eq("WEISHT_DELETED", 0);
//
        weightSheetsWrapper.isNotNull("WEISHT_PRICE_ID");
        weightSheetsWrapper.isNotNull("WEISHT_PRICE_TYPE");
        List<CWeightSheets> weightSheets = weightSheetsService.list(weightSheetsWrapper);
        for (CWeightSheets weightSheet : weightSheets) {
            CWeightSheets cWeightSheets = new CWeightSheets();
            cWeightSheets.setId(weightSheet.getId());
            cWeightSheets.setWeightSpecialPrice(BigDecimal.valueOf(0));
            cWeightSheets.setWeishtPrice(BigDecimal.valueOf(0));
            cWeightSheets.setWeishtMarketPrice(BigDecimal.valueOf(0));
            cWeightSheets.setWeishtMoney(BigDecimal.valueOf(0));
            cWeightSheets.setWeishtPriceId("");
            cWeightSheets.setWeishtPriceType("");
            weightSheetsService.updateById(cWeightSheets);
        }
    }

//    获取磅单图片
    public SzResult getWeightSheetImg(String weightSheetsNo) {
        if(systemConfigReader.isLocalOrCloud().equals("1")){
            return SzResult.error("云服务端暂不支持查看图片");
        }
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("weipicIn1", null);
        paramsMap.put("weipicIn2", null);
        paramsMap.put("weipicOut1", null);
        paramsMap.put("weipicOut2", null);
                    try {
                        WeightPictures weightPictures = weightPicturesMapper.selectBySheetNo(weightSheetsNo);
                        if (weightPictures != null) {
                            if (weightPictures.getWeipicIn1() != null) {
                                String CAR_TAIL_PIC = Base64.getEncoder().encodeToString(weightPictures.getWeipicIn1());
                                paramsMap.put("weipicIn1", CAR_TAIL_PIC);
                            }
                            if (weightPictures.getWeipicIn2() != null) {
                                String CAR_TAIL_PIC = Base64.getEncoder().encodeToString(weightPictures.getWeipicIn2());
                                paramsMap.put("weipicIn2", CAR_TAIL_PIC);
                            }
//车头照片
                            if (weightPictures.getWeipicOut1() != null) {
                                String CAR_HEAD_PIC = Base64.getEncoder().encodeToString(weightPictures.getWeipicOut1());
                                paramsMap.put("weipicOut1", CAR_HEAD_PIC);
                            }
//                车尾照片
                            if (weightPictures.getWeipicOut2() != null) {
                                String CAR_TAIL_PIC = Base64.getEncoder().encodeToString(weightPictures.getWeipicOut2());
                                paramsMap.put("weipicOut2", CAR_TAIL_PIC);
                            }
                        }
                        return SzResult.success(paramsMap);
                    }catch (Exception e){
                        return SzResult.error("获取磅单图片失败");
                    }
    }

    public SzResult getSamplingImg(String weipicSheetno) {
        CWeightPicturesSampling selectBySheetNo = cWeightPicturesSamplingMapper.selectBySheetNo(weipicSheetno);
        if (selectBySheetNo == null) {
            return SzResult.error("没有采样图片");
        }
        return SzResult.success(selectBySheetNo);
    }

    public void samplingUpload(WeightPicturesSamplingBo weightPicturesSamplingBo) {
        CWeightPicturesSampling selectBySheetNo = cWeightPicturesSamplingMapper.selectBySheetNo(weightPicturesSamplingBo.getWeipicSheetno());
        if (selectBySheetNo == null) {
            CWeightPicturesSampling weightPicturesSampling = samplingUploadBase64Handle(weightPicturesSamplingBo);
            weightPicturesSampling.setWeipicSheetno(weightPicturesSamplingBo.getWeipicSheetno());
            cWeightPicturesSamplingMapper.insert(weightPicturesSampling);
        }else {
            CWeightPicturesSampling weightPicturesSampling = samplingUploadBase64Handle(weightPicturesSamplingBo);
            weightPicturesSampling.setId(selectBySheetNo.getId());
           cWeightPicturesSamplingMapper.updateById(weightPicturesSampling);
        }
    }
    //处理采样base64字符串
    private CWeightPicturesSampling samplingUploadBase64Handle(WeightPicturesSamplingBo weightPicturesSamplingBo) {
        CWeightPicturesSampling weightPicturesSampling = new CWeightPicturesSampling();

        // 使用 processImageData 方法处理每个图片字段
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp1())) {
            weightPicturesSampling.setWeipicSamp1(processImageData(weightPicturesSamplingBo.getWeipicSamp1()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp2())) {
            weightPicturesSampling.setWeipicSamp2(processImageData(weightPicturesSamplingBo.getWeipicSamp2()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp3())) {
            weightPicturesSampling.setWeipicSamp3(processImageData(weightPicturesSamplingBo.getWeipicSamp3()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp4())) {
            weightPicturesSampling.setWeipicSamp4(processImageData(weightPicturesSamplingBo.getWeipicSamp4()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp5())) {
            weightPicturesSampling.setWeipicSamp5(processImageData(weightPicturesSamplingBo.getWeipicSamp5()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp6())) {
            weightPicturesSampling.setWeipicSamp6(processImageData(weightPicturesSamplingBo.getWeipicSamp6()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp7())) {
            weightPicturesSampling.setWeipicSamp7(processImageData(weightPicturesSamplingBo.getWeipicSamp7()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp8())) {
            weightPicturesSampling.setWeipicSamp8(processImageData(weightPicturesSamplingBo.getWeipicSamp8()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp9())) {
            weightPicturesSampling.setWeipicSamp9(processImageData(weightPicturesSamplingBo.getWeipicSamp9()));
        }
        if (StringUtils.isNotEmpty(weightPicturesSamplingBo.getWeipicSamp10())) {
            weightPicturesSampling.setWeipicSamp10(processImageData(weightPicturesSamplingBo.getWeipicSamp10()));
        }

        return weightPicturesSampling;
    }
    private byte[] processImageData(String imageData) {
        if (imageData == null || imageData.isEmpty()) {
            return null;
        }

        try {
            // 修复格式错误
            String fixedData = imageData
                    .replace("dataimage/", "data:image/")
                    .replace("/jpegbase64,", "/jpeg;base64,")
                    .replace("/pngbase64,", "/png;base64,")
                    .replace("/gifbase64,", "/gif;base64,");

            // 提取逗号后的纯Base64部分
            int commaIndex = fixedData.indexOf(',');
            if (commaIndex != -1) {
                String pureBase64 = fixedData.substring(commaIndex + 1);

                // 进一步提取从图片数据标记开始的部分
                String finalBase64 = extractPureBase64(pureBase64);
                return Base64.getDecoder().decode(finalBase64);
            } else {
                // 如果没有逗号，直接提取纯Base64部分
                String finalBase64 = extractPureBase64(imageData);
                return Base64.getDecoder().decode(finalBase64);
            }
        } catch (Exception e) {
            log.warn("处理图片数据失败: " + e.getMessage());
            return null;
        }
    }
    /**
     * 安全地解码 Base64 字符串，自动处理 data URL 前缀
     */
//    private byte[] safeBase64Decode(String base64String) {
//        if (StringUtils.isEmpty(base64String)) {
//            return null;
//        }
//
//        try {
//            // 提取纯 Base64 部分
//            String pureBase64 = extractPureBase64(base64String);
//            return Base64.getDecoder().decode(pureBase64);
//        } catch (IllegalArgumentException e) {
//            // 记录日志，可以根据需要处理异常
//            System.err.println("Base64 解码失败: " + e.getMessage());
//            throw new RuntimeException("Base64 解码失败: " + e.getMessage(), e);
//        }
//    }

    /**
     * 从字符串中提取纯 Base64 部分
     * 如果包含 data URL 前缀，则移除前缀；否则返回原字符串
     */
    private String extractPureBase64(String input) {
        if (input.startsWith("data:")) {
            int base64Index = input.indexOf("base64,");
            if (base64Index != -1) {
                return input.substring(base64Index + 7); // 7 是 "base64," 的长度
            }
        }
        return input;
    }

    //    存储视频地址
    public void uploadVideoPath(String weightSheetNo,String videoPath) {

            CWeightPicturesSampling selectBySheetNo = cWeightPicturesSamplingMapper.selectBySheetNo(weightSheetNo);
            if (selectBySheetNo == null) {
                CWeightPicturesSampling weightPicturesSampling = new CWeightPicturesSampling();
                weightPicturesSampling.setWeipicSheetno(weightSheetNo);
                weightPicturesSampling.setWeipicSamp11(videoPath);
                cWeightPicturesSamplingMapper.insert(weightPicturesSampling);
            } else {
                CWeightPicturesSampling weightPicturesSampling = new CWeightPicturesSampling();
                weightPicturesSampling.setId(selectBySheetNo.getId());
                weightPicturesSampling.setWeipicSamp11(videoPath);
                cWeightPicturesSamplingMapper.updateById(weightPicturesSampling);
            }
    }

//    重置downId11为0
    public void resetDownId11(String id) {
        CWeightSheets weightSheet = new CWeightSheets();
        weightSheet.setId(id);
        weightSheet.setDownedID11(0);
        cWeightSheetsMapper.updateById(weightSheet);
    }

//从数据库中获取图片
public void testGetSamplingImg1BySheetNo() {
    // 替换为一个真实存在的、有图片数据的单号
    String sheetNo = "No20230823000926200";
    CWeightPicturesSampling cWeightPicturesSampling = cWeightPicturesSamplingMapper.selectBySheetNo(sheetNo);


    String base64Image = Base64.getEncoder().encodeToString(cWeightPicturesSampling.getWeipicSamp1());
    if (base64Image != null && !base64Image.isEmpty()) {
        System.out.println("✅ 成功获取图片1数据（Base64）:");
        System.out.println("=================================================================");
        System.out.println(base64Image);
        System.out.println("=================================================================");
        System.out.println("Base64 长度: " + base64Image.length());
        System.out.println("提示：可将上面的 Base64 复制到 https://codebeautify.org/base64-to-image 查看图片");
    } else {
        System.out.println("❌ 图片1（weipicSamp1）为空，该单号可能未上传图片1");
    }
}
}
